//
//  CZStatusPictureView.swift
//  weibo
//
//  Created by Apple on 16/3/16.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  重用标记
private let pictureViewIdentifier = "pictureViewIdentifier"

//  每一个图片直接的简介
let itemMargin: CGFloat = 5
//  计算每一个图片的宽度和高度,先转成整数，在包装成CGFloat防止循环计算，防止图片大小不固定可以滚动，可以向下取整不保留小数
let itemWH: CGFloat = CGFloat(Int(UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin - 2 * itemMargin) / 3)

//  微博配图
class CZStatusPictureView: UICollectionView,SDPhotoBrowserDelegate {
    
    var picUrls: [CZStatusPictureInfo]? {
        didSet {
            countLabel.text = "\(picUrls?.count ?? 0)"
            
            //  当前控件更改的约束不是其他控件的约束，可以使用snp_updateConstraints直接更新
            //  如果更新的是其他控件的约束，这个时候需要记录上次的约束，卸载完以后再更新
            snp_updateConstraints { (make) -> Void in
                make.size.equalTo(self.pictureViewSize(picUrls?.count ?? 0))
            }
            
            
            
            reloadData()
        }
    }

    // MARK:    懒加载控件   
    private lazy var countLabel = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 18)
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        //  方式1.
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWH, height: itemWH)
        flowLayout.minimumInteritemSpacing = itemMargin
        flowLayout.minimumLineSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        //  强转方式2
//        let flowlayout1 = self.collectionViewLayout as! UICollectionViewFlowLayout
//        flowlayout1.itemSize = CGSize(width: itemWH, height: itemWH)
//        flowLayout.minimumInteritemSpacing = itemMargin
//        flowlayout1.minimumLineSpacing = itemMargin
        dataSource = self
        delegate = self
        setupUI()
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        registerCollectionViewCell()
        
        addSubview(countLabel)
        
        countLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self)
        }
    }
    private func registerCollectionViewCell() {
    
        self.registerClass(CZStatusPictureViewCell.self, forCellWithReuseIdentifier: pictureViewIdentifier)
    }
    
    // MARK:    计算当前控件的size大小
    private func pictureViewSize(count: Int) -> CGSize {
    
       
        //  判断图片个数是否大于3张，如果大于三种显示三列，否则显示count个数
        let col = count == 4 ? 2 : (count > 3 ? 3: count)
        
        //  显示的行数
        let row = count == 4 ? 2 : ((count - 1) / 3 + 1)
        
        //  计算当前视图的宽度
        let pictureViewWidth = CGFloat(col) * itemWH + (CGFloat(col) - 1) * itemMargin
        //  计算当前视图的高度
        let pictureViewHight = CGFloat(row) * itemWH + (CGFloat(row) - 1) * itemMargin
        
        return CGSize(width: pictureViewWidth, height: pictureViewHight)
        
        
    }
    
}

//  UICollectionViewDataSource 代理方法
extension CZStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewIdentifier, forIndexPath: indexPath) as! CZStatusPictureViewCell
        cell.picUrl = picUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        
        //        SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
        //
        //        browser.sourceImagesContainerView = 原图的父控件;
        //
        //        browser.imageCount = 原图的数量;
        //
        //        browser.currentImageIndex = 当前需要展示图片的index;
        //
        //        browser.delegate = 代理;
        //
        //        [browser show]; // 展示图片浏览器
        
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView =  self
      
        browser.imageCount =  picUrls?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
        
    }

    
}
//  browser代理方法
extension CZStatusPictureView {
  
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let urlString = picUrls![index].thumbnail_pic!.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        
        return NSURL(string: urlString)

    }
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        if let cell = self.cellForItemAtIndexPath(indexPath) as? CZStatusPictureViewCell {
            return cell.imageView.image
        }
        //  返回默认图片
        return UIImage()
    }
    
}


//  自定义cell
class CZStatusPictureViewCell: UICollectionViewCell {
    
    var picUrl: CZStatusPictureInfo? {
        didSet {
            if let imageUrl = picUrl?.thumbnail_pic {
                
//                if imageUrl.hasSuffix(".gif") {
//                    gifImageView.hidden = false
//                } else {
//                    gifImageView.hidden = true
//                }
                
                gifImageView.hidden = !imageUrl.hasSuffix(".gif")
                
                imageView.sd_setImageWithURL(NSURL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
            }
            
        }
    }
    
    // MARK:    懒加载
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        //  设置图片的等比填充模式
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        //  超出部分剪切掉
        imageView.clipsToBounds = true
        return imageView
    }()
    
    private lazy var gifImageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
    
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        
        imageView.snp_makeConstraints { (make) -> Void in
//            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
            make.edges.equalTo(UIEdgeInsetsZero)
        }
        
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.equalTo(imageView)
            make.bottom.equalTo(imageView)
        }
    }
}

